package Ui;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;

import javax.swing.JLabel;
import javax.swing.JLayeredPane;

/*
 * @author Paolo Cordova
 */

public class ActionMessage extends JLabel
{
	
	private static ActionMessage INSTANCE;
	
	private int screenWidth = DisplayAssembler.getScreenWidth();
	private int leftSide = DisplayAssembler.getBoxSize() + 7;
	private int rightSide = leftSide + DisplayAssembler.getSpaceWidth() * 9;
	private int totalSize = rightSide - leftSide;
	private Font actionFont[];
	private int numOfFonts = 35;
	
	static final long serialVersionUID = 101;

	public static ActionMessage getInstance()
	{
		if (INSTANCE == null)
			INSTANCE = new ActionMessage();
		
		return INSTANCE;
	}
	
	private ActionMessage()
	{
		actionFont = new Font[numOfFonts];
		
		for (int i = 0; i < numOfFonts; i++)
			actionFont[i] = new Font("SansSerif", Font.BOLD, (i+1));
		
		this.setForeground(Color.yellow);
		this.setBounds(0, 0, screenWidth, 100);
		this.setVisible(true);
		DisplayAssembler.getInstance().addComponent(this, 0, 0, JLayeredPane.POPUP_LAYER);
	}

	public void newMessage(final String message) {
		
		final int maxFontSize = findProperSize(message);

		new Thread()
		{
			public void run()
			{
				synchronized(ActionMessage.this) 
				{
					ActionMessage.this.setFont(actionFont[0]);
					ActionMessage.this.setText(message);
					setLocation(message, 0);
					ActionMessage.this.setVisible(true);
				
					try 
					{
						for (int i = 0; i < maxFontSize; i++) 
						{
							setLocation(message, i);
							ActionMessage.this.setFont(actionFont[i]);
						
							Thread.sleep(8);
						}

						Thread.sleep(2000);
						
					}
					
					catch (InterruptedException e)
					{
						e.printStackTrace();
					}
				
					ActionMessage.this.setVisible(false);
				}
			}
		}.start();
	}

	private int findProperSize(String message)
	{
		int size = numOfFonts - 1;
		
		while(DisplayAssembler.getInstance().getFontMetrics(actionFont[size]).stringWidth(message) > totalSize)
		{
			size-=2;
		}
		
		return size;
	}
	
	private void setLocation(String message, int fontSelection)
	{
		
		FontMetrics metrics = DisplayAssembler.getInstance().getFontMetrics(actionFont[fontSelection]);
		
		DisplayAssembler.getInstance().animateComponentLocation(this, 
				(leftSide + ((rightSide - leftSide) / 2) - (metrics.stringWidth(message)) / 2), 
				leftSide - metrics.getHeight() + 10);
	}
}
